package com.nearby.android;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnFocusChangeListener;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class Setup extends Activity implements OnFocusChangeListener{
	private EditText serverip;
	private EditText serverport;
	private EditText interval;
	private RadioGroup is_daemon;
	
	private RadioButton checkRadio;
	
	private SharedPreferences preference;
	private SharedPreferences.Editor editor;
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.setup);
		
		initWin();
		initBind();
	}
	public void initWin(){
		serverip = (EditText) findViewById(R.id.serverip);
		serverport = (EditText) findViewById(R.id.serverport);
		interval = (EditText) findViewById(R.id.interval);
		is_daemon = (RadioGroup) findViewById(R.id.is_daemon);
		

		preference = getSharedPreferences("com.nearby.android", MODE_PRIVATE);
		editor = preference.edit();
		
		//初始化值
		String p_value = preference.getString("serverip", "");
		serverip.setText(p_value);
		
		p_value = preference.getString("serverport", "");
		serverport.setText(p_value);
		
		p_value = preference.getString("interval", "");
		interval.setText(p_value);
		
		p_value = preference.getString("is_daemon", "否");
		if(p_value == "是"){
			checkRadio = (RadioButton) findViewById(R.id.is_daemon_yes);
			checkRadio.setChecked(true);
		}else if(p_value == "否"){
			checkRadio = (RadioButton) findViewById(R.id.is_daemon_no);
			checkRadio.setChecked(true);
		}
	}
	public void initBind(){
		serverip.setOnFocusChangeListener(this);
		serverport.setOnFocusChangeListener(this);
		interval.setOnFocusChangeListener(this);
		is_daemon.setOnCheckedChangeListener(new MyCheckChangeListener());
	}
	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		if(v instanceof EditText){
			EditText t = (EditText)v;
			if(t.hasFocus() == false){
				//失去焦点
				switch(t.getId()){
					case R.id.serverip:
						editor.putString("serverip", t.getText().toString().trim());
					break;
					
					case R.id.serverport:
						editor.putString("serverport", t.getText().toString().trim());
						break;
						
					case R.id.interval:
						editor.putString("interval", t.getText().toString().trim());
						break;
				}
				
				editor.commit();
			}
		}
	}
	
	class MyCheckChangeListener implements RadioGroup.OnCheckedChangeListener{
		@Override
		public void onCheckedChanged(RadioGroup group, int checkedId) {
			RadioButton checkRadio = (RadioButton) findViewById(checkedId);
			String checkValue = checkRadio.getText().toString().trim();
			editor.putString("is_daemon", checkValue);
			editor.commit();
		}
	}
	
	
}
